# Handles Zeemote remote device input on PC, control mouse with remote
# Copyright (C) 2009  Aleksandar Kordic

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# download and install: http://www.autoitscript.com/cgi-bin/getfile.pl?autoit3/autoit-v3-setup.exe

import win32com.client
au3 = win32com.client.Dispatch('AutoItX3.Control')

def moveMouse(dx, dy, d=30):
	au3.MouseMove(int(au3.MouseGetPosX() + dx*d), int(au3.MouseGetPosY() + dy*d), 0)

# abs_x, abs_y = au3.MouseGetPosX(), au3.MouseGetPosY()
# def moveMousePrecise(dx, dy, d=30):
	# global abs_x, abs_y
	# if 1:
		# print 'in', dx, dy 
		# c = complex(dx, dy)
		# mag = abs(c)
		# c *= (mag ** 2.0)
		# dx, dy = c.real, c.imag
		# print 'out', dx, dy 
	
	# abs_x += dx*d
	# abs_y += dy*d
	# au3.MouseMove(int(abs_x), int(abs_y), 0)

diff_x, diff_y = 0, 0
BOOST_TRESHOLD = 0.984
def moveMousePrecise2(dx_, dy_, d=30):
	global diff_x, diff_y

	dx = dx_ ** 2.0
	if dx > BOOST_TRESHOLD: dx *= 2.0
	if dx_ < 0: dx = -dx
	dy = dy_ ** 2.0 
	if dy > BOOST_TRESHOLD: dy *= 2.0
	if dy_ < 0: dy = -dy
	#print dx, dy
	
	dx = (dx * d) + diff_x
	dy = (dy * d) + diff_y
	diff_x = dx - int(dx)
	diff_y = dy - int(dy)
	au3.MouseMove(int(au3.MouseGetPosX() + dx), int(au3.MouseGetPosY() + dy), 0)

buttonMap = { 0: 'left', 1: 'right', 2: 'middle' }

def mouseAction(button, actionFn):
	if button in buttonMap:
		#print button, actionFn
		actionFn(buttonMap[button])
	else:
		print 'unknown button %r' % (button, )

def mouseDown(button): mouseAction(button, au3.MouseDown)
def mouseUp(button): mouseAction(button, au3.MouseUp)

activeButtons = set()
def mouseButtons(buttons):
	global activeButtons
	btnSet = set(buttons)
	for btn in btnSet - activeButtons:
		mouseDown(btn)
	for btn in activeButtons - btnSet:
		mouseUp(btn)
	activeButtons = btnSet

